package pojo;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;

@Entity
@Table(name = "LeagueMember")
public class LeagueMember {
	@Embeddable
	public static class Id implements Serializable {
		
		/**
		 * 
		 */
		private static final long serialVersionUID = 1354205426245814752L;
		
		@Column(name = "league_id")
		private int leagueId;
		
		public int getLeagueId() {
			return leagueId;
		}

		@Column(name = "player_id")
		private String playerId;
		
		public Id() {}

		public Id(int leagueId, String playerId) {
			super();
			this.leagueId = leagueId;
			this.playerId = playerId;
		}
		
		public boolean equals(Object o) {
			if (o != null && o instanceof Id) {
				Id that = (Id)o;
				return this.leagueId == that.leagueId && this.playerId.equals(that.playerId);
			} else {
				return false;
			}
		}
		
		public int hashCode() {
			return playerId.hashCode() + leagueId;
		}
	}
	
	@EmbeddedId
	private Id id = new Id();
	
	public Id getId() {
		return id;
	}
	
	@Column(name = "league_score")
    private int leagueScore;

	@ManyToOne
	@NotFound(action=NotFoundAction.IGNORE)
    @JoinColumn(name="league_id",
				insertable = false, updatable = false)
	private League league;
	
	@ManyToOne
    @JoinColumn(name="player_id",
    			insertable = false, updatable = false)
	private UserAccount player;
	
	public LeagueMember(League league, UserAccount player, int leagueScore) {
		// Set fields
		this.league = league;
		this.player = player;
		this.leagueScore = leagueScore;
		
		// Set identifier values
		this.id.leagueId = league.getLeagueId();
		this.id.playerId = player.getUsername();
		
		// Guarantee referential integrity
		/*league.getLeagueMembersForLeague().add(this);
		player.getLeagueMembersForLeague().add(this);*/
	}

	public LeagueMember() {}
	
	public League getLeague() {
		return league;
	}

	public void setLeague(League league) {
		this.league = league;
	}

	public UserAccount getPlayer() {
		return player;
	}

	public void setPlayer(UserAccount player) {
		this.player = player;
	}
	
	public int getLeagueScore() {
		return leagueScore;
	}

	public void setLeagueScore(int leagueScore) {
		this.leagueScore = leagueScore;
	}
}
